package com.tool.permission.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.ContextLoader;

import com.tool.permission.SecurityManager;
import com.tool.permission.model.Resource;
import com.tool.permission.subject.WebSubject;

public class SecurityUtils {
	
	private static final String WEB_SUBJECT_SESSION_KEY = "webSubjectSessionKey";

	private static SecurityManager securityManager;
	
	public static SecurityManager getSecurityManager() {
		if(SecurityUtils.securityManager == null) {
			SecurityUtils.securityManager = ContextLoader.getCurrentWebApplicationContext().getBean(SecurityManager.class);
		}
		return SecurityUtils.securityManager;
	}
	
	public static WebSubject getWebSubject(HttpServletRequest request) {
		WebSubject webSubject = (WebSubject) request.getSession().getAttribute(WEB_SUBJECT_SESSION_KEY);
		if(webSubject == null) {
			Object userid = getSecurityManager().getUserId(request);
			List<Resource> resources = getSecurityManager().getUserResources(userid,request);
			webSubject = new WebSubject(resources,userid);
			request.getSession().setAttribute(WEB_SUBJECT_SESSION_KEY, webSubject);
		}
		return webSubject;
	}
}
